package com.test.demos.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.test.demos.mapper.AppointmentsMapper;
import com.test.demos.mapper.EvaluationsMapper;
import com.test.demos.mapper.MedicalInstitutionsMapper;
import com.test.demos.mapper.UsersMapper;
import com.test.demos.pojo.dto.MedicalPackagesDTO;
import com.test.demos.pojo.entity.Appointments;
import com.test.demos.pojo.entity.Evaluations;
import com.test.demos.pojo.entity.MedicalInstitutions;
import com.test.demos.pojo.entity.MedicalPackages;
import com.test.demos.mapper.MedicalPackagesMapper;
import com.test.demos.pojo.entity.Users;
import com.test.demos.pojo.vo.EvaluationsVO;
import com.test.demos.pojo.vo.MedicalPackagesDetailVO;
import com.test.demos.pojo.vo.MedicalPackagesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.test.demos.service.MedicalPackagesService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.test.demos.pojo.entity.table.AppointmentsTableDef.APPOINTMENTS;
import static org.springframework.util.ObjectUtils.isEmpty;

/**
 * (MedicalPackages)表服务接口
 *
 * @author twt
 * @since 2025-04-14 16:26:55
 */
@Service
@Transactional
public class MedicalPackagesServiceImpl implements MedicalPackagesService {

    @Autowired
    private MedicalPackagesMapper medicalPackagesMapper;

    @Autowired
    private MedicalInstitutionsMapper medicalInstitutionsMapper;

    @Autowired
    private AppointmentsMapper appointmentsMapper;

    @Autowired
    private EvaluationsMapper evaluationsMapper;

    @Autowired
    private UsersMapper usersMapper;

    /**
     * 详细
     *
     * @param packageId 主键
     * @return 实例对象
     */

    @Override
    public MedicalPackagesDetailVO queryById(Integer packageId) {
        // 检查传入的 packageId 是否为空
        if (packageId == null) {
            throw new IllegalArgumentException("套餐 ID 不能为空");
        }

        // 查询套餐信息
        MedicalPackages select = medicalPackagesMapper.selectOneById(packageId);
        if (ObjectUtils.isEmpty(select)) {
            throw new RuntimeException("未查询到对应数据");
        }

        MedicalPackagesDetailVO medicalPackagesDetailVO = new MedicalPackagesDetailVO();
        // 将套餐信息复制到 VO 中
        BeanUtils.copyProperties(select, medicalPackagesDetailVO);

        // 查询机构信息并设置机构名称
        MedicalInstitutions medicalInstitutions = medicalInstitutionsMapper.selectOneById(select.getInstitutionId());
        if (medicalInstitutions != null) {
            medicalPackagesDetailVO.setInstitutionName(medicalInstitutions.getInstitutionName());
        }

        // 构建查询预约记录的条件
        QueryWrapper appointmentQueryWrapper = new QueryWrapper()
                .where(Appointments::getPackageId).eq(packageId)
                .where(Appointments::getStatus).eq(2);

        // 查询预约完成的预约记录的 ID 列表
        List<Appointments> appointments = appointmentsMapper.selectListByQuery(appointmentQueryWrapper);
        List<Integer> appointmentIds = appointments != null ?
                appointments.stream()
                        .map(Appointments::getAppointmentId)
                        .collect(Collectors.toList()) :
                Collections.emptyList();
        System.out.println("appointments = " + appointmentIds);
        // 构建查询评价的条件
        QueryWrapper evaluationQueryWrapper = new QueryWrapper();
        if (CollectionUtils.isEmpty(appointmentIds)) {
            return medicalPackagesDetailVO;
        }
        evaluationQueryWrapper.in("appointment_id", appointmentIds);
        List<Evaluations> evaluations = evaluationsMapper.selectListByQuery(evaluationQueryWrapper);
        // 处理评价信息并设置到 VO 中
        if (!CollectionUtils.isEmpty(evaluations)) {
            List<EvaluationsVO> evaluationsVOList = evaluations.stream()
                    .map(evaluation -> {
                        EvaluationsVO evaluationsVO = new EvaluationsVO();
                        // 获取用户姓名
                        Integer userId = evaluation.getUserId();
                        if (userId != null) {
                            Users users = usersMapper.selectOneById(userId);
                            if (users != null) {
                                evaluationsVO.setName(users.getName());
                            }
                        }
                        BeanUtils.copyProperties(evaluation, evaluationsVO);
                        return evaluationsVO;
                    })
                    .collect(Collectors.toList());
            medicalPackagesDetailVO.setEvaluations(evaluationsVOList);
        }
        return medicalPackagesDetailVO;
    }
    /**
     * 插入数据
     *
     * @param dto
     */
    @Override
    public void add(MedicalPackagesDTO dto) {
        MedicalPackages medicalPackages = new MedicalPackages();
        BeanUtils.copyProperties(dto, medicalPackages);
        Integer pkValue = medicalPackages.getPackageId();

        if (medicalPackagesMapper.selectOneById(pkValue) != null) {
            throw new RuntimeException("数据已存在，无法插入");
        }
        int insert = medicalPackagesMapper.insert(medicalPackages);
        if (insert != 1) {
            throw new RuntimeException("插入数据失败");
        }
    }

    @Override
    public List<MedicalPackagesVO> queryAll() {
        List<MedicalPackages> medicalPackages = medicalPackagesMapper.selectAll();
        // 使用 Stream API 将 MedicalPackages 列表转换为 MedicalPackagesVO 列表
        return medicalPackages.stream()
                .map(medicalPackage -> {
                    MedicalPackagesVO medicalPackagesVO = new MedicalPackagesVO();
                    BeanUtils.copyProperties(medicalPackage, medicalPackagesVO);
                    return medicalPackagesVO;
                })
                .collect(java.util.stream.Collectors.toList());
    }


    /**
     * 更新数据
     *
     * @param medicalPackages
     */
    @Override
    public void update(MedicalPackages medicalPackages) {
        int i = medicalPackagesMapper.update(medicalPackages);
        if (i != 1) {
            throw new RuntimeException("更新数据失败");
        }
    }

    /**
     * 根据主键删除数据
     *
     * @param packageId
     */
    @Override
    public void deleteById(Integer packageId) {
        int i = medicalPackagesMapper.deleteById(packageId);
        if (i != 1) {
            throw new RuntimeException("删除数据失败");
        }
    }

}
